<?php

namespace app\index\controller;

use app\index\model\Attribute;
use app\index\model\Brand;
use app\index\model\Comments;
use app\index\model\ShopCart;
use think\Cache;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Request;
use think\View;

class Goods extends Controller
{

    /**
     * 显示资源列表
     *商品列表
     */
    public function goodsList()
    {
        //获取分类
        $result = Db('type')
            ->where("pid=0")
            ->limit(2)
            ->select();
        $type = $this->getType($result);
        View::share('type', $type);


        //获取分类id
        $id = input('id', 0);
        //删选的商标
        $brand_id=input('brand_id', '');

        //分类下商品条件
        $where=[];
        if (!empty($id)){
            $where['id']=$id;
        }
        if (!empty($brand_id)){
            $where['brand_id']=$brand_id;
        }

        // 商品排序
        $orders = [];
        $order_sales = input('order_sales','');
        $order_price = input('order_price','');
        $order_time = input('order_time','');
        if(!empty($order_sales)) {
            $orderflag = 'order_sales';
            $orders['inventory'] = $order_sales;
        }elseif(!empty($order_price)) {
            $orderflag = 'order_price';
            $orders['purchase_price'] = $order_price;
        }elseif(!empty($order_time)) {
            $orderflag = 'order_time';
            $orders['time'] = $order_time;
        }else{
            $orderflag = '';
        }
        $good=new \app\index\model\Goods();
        $goods=$good->getConditionGoods($where,$orders);


        //品牌
        $brand=Brand::all();

        //推荐热卖
        $hot_recommend=$good->getHotGoods($id);

        //新品推荐
        $new_recommend=$good->getNewGoods($id);


        $event = \think\Loader::controller('Goods', 'widget');
        $shopCart = $event->topHeader();

//        return jj($goods);
        $this->assign(
            [
                'goods'=>$goods,
                'brand'=>$brand,
                'hot_recommend'=>$hot_recommend,
                'new_recommend'=>$new_recommend,
                'id'=>$id,
                'orderflag'=>$orderflag,
                'shopCart'=>$shopCart,
            ]
        );
        return view();
    }




    /**
     * 商品详情
     */
    public function goodsInfo()
    {
        //获取分类id
        $id = input('id', 0);

        //获取属性id
        $attr=input('attr_id');
        if (empty($attr)){
            $goods=(new \app\index\model\Goods())->getGoods($id);
        }else{
            $goods=(new \app\index\model\Goods())->getAllGoods($id,$attr);
        }



        //获取商品详情

//        return jj($goods);
        //评论统计
        $comment=new Comments();
//        $comment_account=$comment->getCommentCount($id);

        //获取该商品的所有评论
        $comments=$comment->getComment($id);

        $event = \think\Loader::controller('Goods', 'widget');
        $shopCart = $event->topHeader();


        //获取分类
        $result = Db('type')
            ->where("pid=0")
            ->limit(2)
            ->select();
        $type = $this->getType($result);
        View::share('type', $type);

        View::share('shopCart', $shopCart);
        //历史记录
        $history=$this->history($id);

        //该商品哪些属性
        $attribute=(new Attribute())->where('goods_id',$id)->select();


        $this->assign(
            [
                'id'=>$id,
                'goods'=>$goods,
                'comments'=>$comments,
                'shopCart' => $shopCart,
                'history'=>$history,
                'attribute'=>$attribute,
                'type'=>$type
            ]
        );
        return view();
    }

    /**
     * 获取分类
     */
    public function getType($type)
    {
        $m = Db('type');
//        $type=$m->where("pid=0")->select();//获取一级分类
        $type2 = array();
        $type3 = array();

        foreach ($type as $key => $value) {
            $type[$key]['child'] = array();//二级分类的名字
            $type2 = $m->where("pid=" . $value['id'])->select();//获取二级分类

            foreach ($type2 as $k => $v) {

                array_push($type[$key]['child'], $v);//合并一级与二级分类
                $type[$key]['child'][$k]['child2'] = array();////三级分类的名字

                $type3 = $m->where("pid=" . $v['id'])->select();//获取三级分类
                foreach ($type3 as $v2) {
                    $v2['goods'] = \app\index\model\Goods::where('type_id', $v2['id'])->join('attribute','goods.id=attribute.goods_id')
                        ->group('goods.id')->SELECT();
                    array_push($type[$key]['child'][$k]['child2'], $v2);//合并一级二级三级分类

                }


            }

        }
        return $type;
    }

    /**
     * 添加评论
     */
     public function saveComment(){
        $input=input('post.');
        $date['level']=$input['grade'];
        $date['comments']=$input['comments'];
        $date['goods_id']=$input['goods_id'];
        $date['user_id']=session("uid");
        $date['time']=date("Y-m-d H:i:s");
        $result=(new Comments())->save($date);
        if ($result){
            $this->success('评论成功');
        }else{
            $this->error('评论失败');
        }
     }


    /**
     * 用户历史记录
     * @param $data
     * @return bool
     */
     public function history($data){
         if (!$data){
             return false;
         }
         //如果有记录
         if (Cookie::get('history_shop')){
             $history=Cookie::get('history_shop');
             array_unshift($history,$data);
             $rows=array();
             foreach ($history as $v){
                 if (in_array($v,$rows))
                 {
                     continue;
                 }
                 $rows[]=$v;
             }
             while (count($rows)>5){
                 array_pop($rows);
             }
             Cookie::set('history_shop',$history,3600);

             foreach ($rows as $k=>$row){
                 $history_shop[$k]=(new \app\index\model\Goods())->getGoods($row);
             }
             return $history_shop;
         }
         else
         {
             $history = array($data);
             Cookie::set('history_shop',$history,3600);
         }


     }

     public function purchase(){

         if (!session('uid')){
             $this->error('请先登录','index/login');
         }
         $input=input('post.');
//                  return jj(input('post.'));
         $res['goods_id']=$input['good_id'];
         $res['color']=$input['color'];
         $res['size']=$input['size'];
         $res['price']=$input['prie'];
         $res['img']=$input['img'];
         $res['num']=$input['amount'];
         $res['user_id']=session('uid');

         $date=(new ShopCart())->save($res);
         if ($date){
             $this->success('购买成功');
         }else{
             $this->error('购买失败');
         }

     }
}
